<template>
  <Page
    title="已办任务"
    description="查看已完成的任务和审批历史"
  >
    <div class="flex h-full flex-col">
      <!-- 查询表单 -->
      <div class="mb-4 rounded-lg bg-white p-4">
        <Form layout="inline" :model="queryParams">
          <FormItem label="流程名称">
            <Input
              v-model:value="queryParams.processDefinitionName"
              placeholder="请输入流程名称"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem label="任务名称">
            <Input
              v-model:value="queryParams.taskName"
              placeholder="请输入任务名称"
              allow-clear
              style="width: 200px"
            />
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleQuery">
                <template #icon><SearchOutlined /></template>
                查询
              </Button>
              <Button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>

      <!-- 数据表格 -->
      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button type="link" size="small" @click="handleViewDetail(row)">
                查看详情
              </Button>
              <Button type="link" size="small" @click="handleViewDiagram(row)">
                流程图
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <Modal
      v-model:open="detailModalVisible"
      title="任务详情"
      width="700px"
      :footer="null"
    >
      <Descriptions :column="2" bordered>
        <DescriptionsItem label="流程名称">
          {{ currentTask?.processDefinitionName }}
        </DescriptionsItem>
        <DescriptionsItem label="任务名称">
          {{ currentTask?.name }}
        </DescriptionsItem>
        <DescriptionsItem label="办理人">
          {{ currentTask?.assignee }}
        </DescriptionsItem>
        <DescriptionsItem label="办理时间">
          {{ currentTask?.endTime }}
        </DescriptionsItem>
        <DescriptionsItem label="耗时" :span="2">
          {{ calculateDuration(currentTask?.startTime, currentTask?.endTime) }}
        </DescriptionsItem>
      </Descriptions>

      <Divider>审批意见</Divider>
      <div v-if="taskComments.length > 0">
        <Timeline>
          <TimelineItem
            v-for="comment in taskComments"
            :key="comment.id"
            color="green"
          >
            <div class="comment-item">
              <div class="comment-header">
                <span class="comment-user">{{ comment.userId }}</span>
                <span class="comment-time">{{ comment.time }}</span>
              </div>
              <div class="comment-content">{{ comment.message }}</div>
            </div>
          </TimelineItem>
        </Timeline>
      </div>
      <Empty v-else description="暂无审批意见" />
    </Modal>
  </Page>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';

import {
  Button,
  Descriptions,
  Divider,
  Empty,
  Form,
  FormItem,
  Input,
  Modal,
  Space,
  Timeline,
  message,
} from 'ant-design-vue';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons-vue';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

const DescriptionsItem = Descriptions.Item;
const TimelineItem = Timeline.Item;

import type { HistoricTask, TaskComment } from '#/api/workflow';
import { getDoneTaskListApi, getTaskCommentsApi } from '#/api/workflow';

// 查询参数
const queryParams = reactive({
  processDefinitionName: undefined,
  taskName: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 表格配置
const [Grid, gridApi] = useVbenVxeGrid<HistoricTask>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'processDefinitionName',
        title: '流程名称',
        minWidth: 200,
      },
      {
        field: 'name',
        title: '任务名称',
        minWidth: 150,
      },
      {
        field: 'assignee',
        title: '办理人',
        width: 120,
      },
      {
        field: 'startTime',
        title: '开始时间',
        minWidth: 180,
      },
      {
        field: 'endTime',
        title: '完成时间',
        minWidth: 180,
      },
      {
        field: 'action',
        title: '操作',
        width: 200,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 详情相关
const detailModalVisible = ref(false);
const currentTask = ref<HistoricTask>();
const taskComments = ref<TaskComment[]>([]);

// 查询列表
async function fetchList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getDoneTaskListApi(queryParams);
    gridApi.setState({
      gridOptions: {
        data: data.list,
        loading: false,
        pagerConfig: {
          currentPage: data.pageNum,
          pageSize: data.pageSize,
          total: data.total,
        },
      },
    });
  } catch (error: any) {
    message.error(error?.msg || '查询失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  fetchList();
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchList();
}

// 重置
function handleReset() {
  queryParams.processDefinitionName = undefined;
  queryParams.taskName = undefined;
  queryParams.pageNum = 1;
  fetchList();
}

// 查看详情
async function handleViewDetail(record: HistoricTask) {
  currentTask.value = record;

  // 加载审批意见
  try {
    taskComments.value = await getTaskCommentsApi(record.id!);
  } catch (error: any) {
    message.error(error?.msg || '加载审批意见失败');
    taskComments.value = [];
  }

  detailModalVisible.value = true;
}

// 查看流程图
function handleViewDiagram(record: HistoricTask) {
  // TODO: 打开流程图查看器
  message.info('功能开发中...');
}

// 计算耗时
function calculateDuration(startTime?: string, endTime?: string): string {
  if (!startTime || !endTime) return '-';

  const start = new Date(startTime).getTime();
  const end = new Date(endTime).getTime();
  const duration = end - start;

  const days = Math.floor(duration / (1000 * 60 * 60 * 24));
  const hours = Math.floor((duration % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));

  const parts = [];
  if (days > 0) parts.push(`${days}天`);
  if (hours > 0) parts.push(`${hours}小时`);
  if (minutes > 0) parts.push(`${minutes}分钟`);

  return parts.length > 0 ? parts.join(' ') : '不到1分钟';
}

// TODO: 后台接口未完成，暂时注释掉自动加载
// onMounted(() => {
//   fetchList();
// });

// 初始化空数据，避免页面报错
onMounted(() => {
  gridApi.setState({
    gridOptions: {
      data: [],
      loading: false,
    },
  });
});
</script>

<style scoped>
.comment-item {
  padding: 8px 0;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.comment-user {
  font-size: 14px;
  font-weight: 500;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-content {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}
</style>

